package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartyFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author : xyq
 * @Description:
 * @date: 2020/7/19/0:49
 */
@Controller
public class LoginController {

    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;    // redis操作工具类
    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 远程调用第三方服务发送短信验证码
     */
    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {
        // todo 1、接口防刷

        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long time = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - time < 60 * 1000) {
                // 同一个手机号，60s内不能再发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        // 2、验证码的再次校验（存储到redis中）存key-phone，value-code
        String code = UUID.randomUUID().toString().substring(0, 5);
        String subStr = code + "_" + System.currentTimeMillis();
        // redis缓存验证码（10分钟有效期），防止同一个phone在60s内再次发送验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, subStr, 10, TimeUnit.MINUTES);

        thirdPartyFeignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * todo 分布式下的session问题
     * RedirectAttributes：模拟重定向携带数据。
     * 重定向携带数据，利用session原理，将数据放入session中。只要跳转到下一个页面取出该数据后，session里面的数据就会删掉。
     */
    @PostMapping("/regist")
    public String register(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            /**
             * Map<String, String> errors = new HashMap<>();
             * .map(fieldError -> {
             *                 String field = fieldError.getField();
             *                 String msg = fieldError.getDefaultMessage();
             *                 errors.put(field,msg);
             *                 return
             *             })
             *
             *             Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> {
             *                 return fieldError.getField();
             *             }, fieldError -> {
             *                 return fieldError.getDefaultMessage();
             *             }));
             *也可以如下：
             */
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//            model.addAttribute("errors", errors);
            redirectAttributes.addFlashAttribute("errors", errors);
            // 校验出错，重定向到注册页（报错：Request method 'POST' not supported，通过thymeleaf直接渲染到reg页面）
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        // 1、校验验证码
        String code = vo.getCode();
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(redisCode)) {
            if (code.equals(redisCode.split("_")[0])) {
                // 删除验证码；令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                // 验证码通过。调用远程服务，进行注册
                R r = memberFeignService.regist(vo);
                if (r.getCode() == 0) {
                    // 注册成功，回到登录页。GulimallWebConfig中映射了登录页的路径地址，只要是本服务要重定向，就可以不加前缀http://auth.gulimall.com
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    /**
     * 去登陆页（已登录用户访问注册页面，直接跳转到首页）
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null) {
            //未登录
            return "login";
        } else {
            return "redirect:http://gulimall.com";
        }
    }

    /**
     * 处理登录请求
     * 页面提交过来的是form表单的kv值，不是json数据，故不使用注解 @RequestBody
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {
        // 远程登录
        R r = memberFeignService.login(vo);
        if (r.getCode() == 0) {
            MemberResponseVo data = r.getData("data", new TypeReference<MemberResponseVo>() {
            });
            // 登录成功，并放入session
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://gulimall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    //----------------------------------------------------------------------------------
    /**
     * 发送一个请求直接跳转到一个页面
     * 使用springMVC提供的viewcontroller功能，来映射一个请求到页面：将请求和页面映射（不用写空方法了）
     */
    /*//跳转到登录页
    @GetMapping("/login.html")
    public String loginPage() {
        return "login";
    }
    //跳转到注册页
    @GetMapping("/reg.html")
    public String regPage() {
        return "reg";
    }*/
}
